import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/index'

import { staticRouter } from './staticRouter'

Vue.use(VueRouter)

const routes = staticRouter

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

let flag = true

router.beforeEach(async (to, from, next) => {
  try {
    const token = localStorage.getItem('tokens')
    if (token) {
      if (flag) {
        flag = false
        await store.dispatch('userAuth/getUserPermissions') // 3.5 以后的bug，新添加的route 不生效，需要手动触发
        return next({ ...to, replace: true })
      } else {
        flag = false
        return next() // 进入此处，直接触发
      }
    } else {
      if (to.path !== '/login') {
        return next('/login')
      }
      if (to.path === '/login') {
        return next()
      }
    }
  } catch (error) {
    console.log(error, 123123)
  }
})

export default router
